package com.example.controller;


import com.example.common.*;
import com.example.dao.Role;
import com.example.dao.User;
import com.example.service.RoleService;
import com.example.service.UserService;
import com.example.util.TotpUtil;
import com.example.validation.DtoValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Nullable;
import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户处理控制器
 */
@RestController
@RequestMapping("/user")
public class UserController {
    /**
     * 用户service
     */
    @Autowired
    private UserService userService;
    /**
     * 角色service
     */
    @Autowired
    private RoleService roleService;
    /**
     * 加密处理器
     */
    @Autowired
    private PasswordEncoder passwordEncoder;
    /**
     * 一次性验证工具类
     */
    @Autowired
    private TotpUtil totpUtil;

    /**
     * 校验器
     */
    @Autowired
    private DtoValidator dtoValidator;

    //    @GetMapping("/me")
//    public String getProfile() {
//        return SecurityUtil.getCurrentLogin();
//    }
//
//    @GetMapping("/principal")
//    public String getCurrentPrincipalName(Principal principal) {
//        return principal.getName();
//    }
//
//    @GetMapping("/authentication")
//    public Authentication getCurrentAuthentication(Authentication authentication) {
//        return authentication;
//    }
    /*
    @RequestMapping(value = "/page")
    public String page(@RequestParam("startIndex") int startIndex,
                       @RequestParam("maxCount") int maxCount,
                       @RequestParam(value = "userAccount",defaultValue ="") String userAccount,
                       @RequestParam(value = "userName",defaultValue ="") String userName, Model model) {
     */

    /**
     * 校验用户账号，用户账号不能重复
     *
     * @param username
     * @param id
     * @return
     */
    @GetMapping("/validateUsername")
    public CommonRes validateUsername(@RequestParam String username, @RequestParam Long id) {
        if (userService.isUsernameExisted(username, id)) {
            return CommonRes.createError(null);
        } else {
            return CommonRes.create(null);
        }
    }

    /**
     * 校验邮箱，邮箱不能重复
     *
     * @param email
     * @param id
     * @return
     */
    @GetMapping("/validateEmail")
    public CommonRes validateEmail(@RequestParam String email, @RequestParam Long id) {
        if (userService.isEmailExisted(email, id)) {
            return CommonRes.createError(null);
        } else {
            return CommonRes.create(null);
        }
    }

    /**
     * 校验手机，手机不能重复
     *
     * @param mobile
     * @param id
     * @return
     */
    @GetMapping("/validateMobile")
    public CommonRes validateMobile(@RequestParam String mobile, @RequestParam Long id) {
        if (userService.isMobileExisted(mobile, id)) {
            return CommonRes.createError(null);
        } else {
            return CommonRes.create(null);
        }
    }

    /**
     * 分页查询用户
     *
     * @param pageNo   第几页
     * @param pageSize 每页显示的数量
     * @param name     查询参数，姓名
     * @param mobile   查询参数，手机
     * @return
     */
    @GetMapping("/page")
    public CommonRes page(@RequestParam("pageNo") int pageNo,
                          @RequestParam("pageSize") int pageSize,
                          @RequestParam(value = "name", defaultValue = "") String name,
                          @RequestParam(value = "mobile", defaultValue = "") String mobile) {
        User user = new User();
        user.setStartIndex(pageNo * pageSize);
        user.setPageSize(pageSize);
        user.setName(name);
        user.setMobile(mobile);
        Integer total = userService.findCount(user);
        List<User> usersList = userService.findUsersByPage(user);
        PageData<User> userData = new PageData<>();
        userData.setTotal(total);
        userData.setPageData(usersList);
        return CommonRes.create(userData);
    }

    /**
     * 分页查询角色，显示哪些角色分配给了某个用户
     *
     * @param pageNo   第几页
     * @param pageSize 每页显示的数量
     * @param userId   查询参数，用户id
     * @return
     */
    @GetMapping("/rolePage")
    public CommonRes rolePage(@RequestParam("pageNo") int pageNo,
                              @RequestParam("pageSize") int pageSize,
                              @RequestParam(value = "userId") Long userId) {
        Role role = new Role();
        role.setStartIndex(pageNo * pageSize);
        role.setPageSize(pageSize);
        Integer total = roleService.findCount(role);
        List<Role> rolesList = roleService.findRolesByPage(role);
        PageDataChecked<Role> roleData = new PageDataChecked<>();
        roleData.setTotal(total);
        roleData.setPageData(rolesList);

        //查询该用户的所有角色
        List<Long> roleIdList = roleService.findRoleIdsByUserId(userId);
        //只是把当前页的被设置过的角色id传过去
        roleIdList = roleIdList.stream().
                filter(roleId -> rolesList.stream().anyMatch(r -> r.getId() == roleId)).
                collect(Collectors.toList());
        roleData.setCheckedList(roleIdList);
        return CommonRes.create(roleData);
    }




    /**
     * 设置用户角色
     * @param addData
     * @param delData
     * @param userId
     * @return
     */
    @PostMapping("/attachRoleToUser")
    public CommonRes attachRoleToUser(@Nullable @RequestParam("addData[]") Long[] addData,@Nullable @RequestParam("delData[]") Long[] delData, @RequestParam("userId") Long userId) {
        int result = roleService.attachRoleToUser(addData,delData,userId);
        if (result > 0) {
            return CommonRes.create(null);
        } else {
            CommonError commonError = new CommonError(BusinessError.UNKNOWN_ERROR);
            return CommonRes.createError(commonError);
        }
    }

    /**
     * 删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping("/delete")
    public CommonRes delete(@RequestBody Long[] ids) {
        int result = userService.deleteUserByIds(ids);
        if (result > 0) {
            return CommonRes.create(null);
        } else {
            CommonError commonError = new CommonError(BusinessError.UNKNOWN_ERROR);
            return CommonRes.createError(commonError);
        }
    }

    /**
     * 新增用户
     *
     * @param user
     * @return
     */
    @PostMapping(value = "/addUser")
    public CommonRes addUser(@Valid @RequestBody User user) {
        // com.example.aspect.ValidateAspect
        //通过aop校验传过来的用户实体类userDto

        //id是autoincrease
        user.setId(null);
        user.setPassword(passwordEncoder.encode("12345678"));
        //用于一次性验证码
        user.setMfaKey(totpUtil.encodeKeyToString());
        int result = userService.insertUser(user);
        if (result > 0) {
            return CommonRes.create(null);
        } else {
            CommonError commonError = new CommonError(BusinessError.UNKNOWN_ERROR);
            return CommonRes.createError(commonError);
        }
    }

    /**
     * 修改用户
     *
     * @param user
     * @return
     */
    @PostMapping(value = "/modifyUser")
    public CommonRes modifyUser(@Valid @RequestBody User user) {
        // com.example.aspect.ValidateAspect
        //通过aop校验传过来的用户实体类userDto

        int result = userService.updateUser(user);
        if (result > 0) {
            return CommonRes.create(null);
        } else {
            CommonError commonError = new CommonError(BusinessError.UNKNOWN_ERROR);
            return CommonRes.createError(commonError);
        }
    }
}
